<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍编辑功能测试</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"],
        input[type="number"],
        textarea,
        select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .image-preview {
            margin-top: 10px;
            text-align: center;
        }
        .image-preview img {
            max-width: 100%;
            max-height: 200px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: none;
        }
        #result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info-box {
            background-color: #e7f3fe;
            border-left: 6px solid #2196F3;
            margin-bottom: 15px;
            padding: 10px;
        }
        .nav-buttons {
            margin-top: 15px;
            display: flex;
            justify-content: space-between;
        }
        .nav-buttons a {
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 4px;
            color: white;
        }
        .nav-buttons .back-button {
            background-color: #6c757d;
        }
        .nav-buttons .back-button:hover {
            background-color: #5a6268;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>校园二手书店 - 书籍编辑测试</h1>
        
        <div class="info-box">
            <p>此页面用于测试书籍编辑功能。请先输入要编辑的书籍ID和JWT Token，然后填写需要修改的字段（空字段将保持不变）。</p>
        </div>
        
        <form id="editBookForm">
            <div class="form-group">
                <label for="token">JWT Token (必填):</label>
                <input type="text" id="token" name="token" placeholder="Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." required>
            </div>
            
            <div class="form-group">
                <label for="book_id">书籍ID (必填):</label>
                <input type="number" id="book_id" name="book_id" placeholder="要编辑的书籍ID" required>
            </div>
            
            <div class="form-group">
                <label for="title">书名:</label>
                <input type="text" id="title" name="title" placeholder="修改后的书名">
            </div>
            
            <div class="form-group">
                <label for="author">作者:</label>
                <input type="text" id="author" name="author" placeholder="修改后的作者">
            </div>
            
            <div class="form-group">
                <label for="category">分类:</label>
                <input type="text" id="category" name="category" placeholder="修改后的分类">
            </div>
            
            <div class="form-group">
                <label for="price">价格:</label>
                <input type="number" id="price" name="price" step="0.01" placeholder="修改后的价格">
            </div>
            
            <div class="form-group">
                <label for="new_degree">新旧程度 (1-100):</label>
                <input type="number" id="new_degree" name="new_degree" min="1" max="100" placeholder="1-100之间的数值">
            </div>
            
            <div class="form-group">
                <label for="description">描述:</label>
                <textarea id="description" name="description" placeholder="修改后的书籍描述"></textarea>
            </div>
            
            <div class="form-group">
                <label for="coverFile">封面图片:</label>
                <input type="file" id="coverFile" accept="image/*">
                <div class="image-preview">
                    <img id="coverPreview" alt="图片预览">
                </div>
            </div>
            
            <button type="submit">提交编辑</button>
        </form>
        
        <div id="result"></div>
        
        <div class="nav-buttons">
            <a href="test_get_book.html" id="backButton" class="back-button">返回查询页面</a>
        </div>
    </div>
    
    <script>
        // 图片预览和Base64转换
        document.getElementById('coverFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            const preview = document.getElementById('coverPreview');
            const reader = new FileReader();
            
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
            }
            
            reader.readAsDataURL(file);
        });
        
        // 表单提交
        document.getElementById('editBookForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取JWT Token
            const token = document.getElementById('token').value.trim();
            if (!token) {
                showResult('JWT Token不能为空', false);
                return;
            }
            
            // 准备请求数据
            const bookData = {
                book_id: parseInt(document.getElementById('book_id').value)
            };
            
            // 添加非空字段
            const fields = ['title', 'author', 'category', 'description'];
            fields.forEach(field => {
                const value = document.getElementById(field).value.trim();
                if (value) bookData[field] = value;
            });
            
            // 添加数值字段
            const price = document.getElementById('price').value.trim();
            if (price) bookData.price = parseFloat(price);
            
            const newDegree = document.getElementById('new_degree').value.trim();
            if (newDegree) bookData.new_degree = parseInt(newDegree);
            
            // 处理图片
            const coverFile = document.getElementById('coverFile').files[0];
            if (coverFile) {
                try {
                    const base64 = await fileToBase64(coverFile);
                    // 从Base64字符串中移除前缀 "data:image/jpeg;base64,"
                    bookData.cover = base64.split(',')[1];
                    bookData.cover_type = coverFile.type;
                } catch (error) {
                    showResult('处理图片时出错: ' + error.message, false);
                    return;
                }
            }
            
            console.log('请求数据:', bookData);
            
            // 发送请求
            try {
                const response = await fetch('http://localhost:8080/api/user/book/editBook', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify(bookData)
                });
                
                const result = await response.json();
                console.log('返回结果:', result);
                
                if (result.code === 200) {
                    showResult(`编辑成功: ${result.message}`, true);
                    
                    // 更新返回按钮，带上书籍ID和token参数
                    updateBackButton(bookData.book_id, token);
                    
                    // 3秒后自动返回到查询页面
                    setTimeout(() => {
                        window.location.href = `test_get_book.html?id=${bookData.book_id}&token=${encodeURIComponent(token)}`;
                    }, 3000);
                } else {
                    showResult(`编辑失败: ${result.message}`, false);
                }
            } catch (error) {
                showResult('请求出错: ' + error.message, false);
            }
        });
        
        // 辅助函数 - 文件转Base64
        function fileToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });
        }
        
        // 显示结果
        function showResult(message, isSuccess) {
            const resultDiv = document.getElementById('result');
            resultDiv.textContent = message;
            resultDiv.className = isSuccess ? 'success' : 'error';
            resultDiv.style.display = 'block';
            
            // 自动滚动到结果区域
            resultDiv.scrollIntoView({ behavior: 'smooth' });
        }
        
        // 更新返回按钮的href
        function updateBackButton(bookId, token) {
            const backButton = document.getElementById('backButton');
            backButton.href = `test_get_book.html?id=${bookId}&token=${encodeURIComponent(token)}`;
        }
        
        // 检查URL参数，自动填充表单
        window.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const id = urlParams.get('id');
            const token = urlParams.get('token');
            
            if (id) {
                document.getElementById('book_id').value = id;
                // 更新返回按钮链接
                updateBackButton(id, token || '');
            }
            
            if (token) {
                document.getElementById('token').value = token;
            }
        });
    </script>
</body>
</html> 